<template>
  <div class="employees-container">
    <div class="app-container">
      <!-- 通用工具栏组件使用 -->
      <page-tools>
        <!-- 自定义左侧内容 -->
        <template #slot-left>
          <span>共 19 条记录</span>
        </template>

        <!-- 自定义右侧内容 -->
        <template #slot-right>
          <el-button v-power="'import'" type="danger" size="small" @click="uploadExcel">
            导入excel
          </el-button>
          <el-button v-power="'export'" type="success" size="small" @click="handleDownload">
            导出excel
          </el-button>
          <el-button type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>

      <!-- table表格 -->
      <el-card style="margin-top: 10px">
        <el-table
          v-loading="loading"
          border
          :data="employeesList"
          :default-sort="{ prop: 'workNumber', order: 'ascending' }"
        >
          <el-table-column align="center" type="index" label="序号" />
          <el-table-column align="center" prop="username" label="姓名" />
          <el-table-column align="center" prop="staffPhoto" label="头像">
            <template v-slot="scope">
              <!-- eslint-disable-next-line -->
              <!-- <img v-if="scope.row.staffPhoto" :src="scope.row.staffPhoto" /> -->
              <!-- eslint-disable-next-line -->
              <!-- <img v-else src="@/assets/common/head.jpg" /> -->
              <image-holder :img="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column align="center" prop="mobile" label="手机号" />
          <el-table-column
            align="center"
            prop="workNumber"
            label="工号"
            sortable
            :sort-method="workNumberSortFn"
          />
          <el-table-column align="center" prop="formOfEmployment" label="聘用形式">
            <template v-slot="scope">
              {{ formatter(scope.row) }}
            </template>
          </el-table-column>
          <el-table-column align="center" prop="departmentName" label="部门" />
          <el-table-column
            align="center"
            prop="timeOfEntry"
            label="入职时间"
            sortable
            :sort-method="timeOfEntrySortFn"
          >
            <template v-slot="scope">
              {{ formatDate(scope.row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="280">
            <template v-slot="scope">
              <el-button
                type="text"
                size="small"
                @click="
                  $router.push(
                    `/employees/detail?id=${scope.row.id}&formOfEmployment=${scope.row.formOfEmployment}`
                  )
                "
              >
                查看
              </el-button>
              <el-button type="text" size="small" @click="showRoleDialogFn(scope.row)">
                分配角色
              </el-button>
              <el-button type="text" size="small" @click="delStaff(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <!-- 分页区域 -->
          <el-pagination
            :current-page="query.page"
            :page-sizes="[10, 15, 20, 25]"
            :page-size="query.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>

      <!-- 新增员工弹窗 -->
      <!-- 新增员工弹框组件 -->
      <el-dialog title="新增员工" :visible.sync="showDialog">
        <emp-dialog
          ref="staffForm"
          :show-dialog.sync="showDialog"
          :tree-data="tree"
          @addStaffEV="addStaff"
        />
      </el-dialog>

      <!-- 权限分配弹框 -->
      <role-dialog
        ref="roleDialog"
        :show-dia.sync="showRoleDialog"
        :role-list="roleList"
        @assignRolesEv="assignRoles"
      />
    </div>
  </div>
</template>

<script>
import {
  getStaffInfoAPI,
  delStaffAPI,
  addStaffAPI,
  getDepartInfoAPI,
  getRoleListAPI,
  getStaffDetailAPI,
  assignRolesAPI
} from '@/api'
import { transTree } from '@/utils'
import enumerate from '@/enumerate.js'
import dayjs from 'dayjs'
import EmpDialog from './components/empDialog'
import RoleDialog from './components/assignRoleDialog.vue'
export default {
  name: 'Employees',
  components: {
    'emp-dialog': EmpDialog,
    'role-dialog': RoleDialog
  },
  data() {
    return {
      query: {
        page: 1, // 页码
        size: 10 // 每页条数
      },
      employeesList: [], // 员工列表
      total: 0, // 数据总条数
      showDialog: false, // 添加员工组件的展示
      tree: [], // 树形控件数据
      excelTable: enumerate.table, // excel导出表
      showRoleDialog: false, // 显示角色弹框
      roleList: [], // 角色列表
      roleId: '', // 员工id
      loading: true
    }
  },
  created() {
    // 获取员工列表
    this.getStaffInfo()
    // 获取部门负责人列表
    this.getDepartInfo()
    // 获取角色列表
    this.getRoleList()
  },

  methods: {
    // 每页显示的条数发生改变时触发
    handleSizeChange(newSize) {
      this.query.size = newSize
      this.getStaffInfo()
    },

    // 当前页面发生改变时触发
    handleCurrentChange(newPage) {
      this.query.page = newPage
      this.getStaffInfo()
    },

    // 获取员工信息列表
    async getStaffInfo() {
      const res = await getStaffInfoAPI(this.query)
      console.log(res)
      this.employeesList = res.data.rows
      this.total = res.data.total
      this.loading = false
    },

    // 枚举对比方法
    formatter(row) {
      // row对应行的数据对象
      const obj = enumerate.hireType.find((item) => {
        return item.id === Number(row.formOfEmployment)
      })
      return obj ? obj.value : '未知'
    },

    // 格式化入职日期
    formatDate(date) {
      return dayjs(date).format('YYYY-MM-DD')
    },

    // 工号排序
    workNumberSortFn(a, b) {
      return parseInt(a.workNumber) - parseInt(b.workNumber)
    },

    // 入职日期排序
    timeOfEntrySortFn(a, b) {
      // 转换为日期对象
      const dateA = new Date(a.timeOfEntry)
      const dateB = new Date(b.timeOfEntry)
      // 时间戳相减
      return dateA.getTime() - dateB.getTime()
    },

    // 删除员工
    async delStaff(staffId) {
      try {
        if (this.employeesList.length === 1 && this.query.page > 1) {
          await delStaffAPI(staffId)
          this.query.page--
        } else {
          await delStaffAPI(staffId)
        }
        // 刷新列表
        this.getStaffInfo()
      } catch (err) {
        console.log(err)
      }
    },

    // 增加员工
    async addStaff({ ...formData }) {
      await addStaffAPI({ ...formData })
      this.getStaffInfo()
    },

    // 获取部门负责人
    async getDepartInfo() {
      const res = await getDepartInfoAPI()
      this.tree = transTree(res.data.depts, '')
    },

    // 跳转到导入excel路由
    uploadExcel() {
      this.$router.push('/upload')
    },

    // 文件导出下载
    transData(rows) {
      // 考虑顺序 (页面上列保持一致顺序)
      // 4.0 准备一个列表头中文数组 (8个)
      const headerArr = ['序号', '姓名', '手机号', '工号', '聘用形式', '部门', '入职时间']
      // 4.1 数据key的映射关系(思路: 遍历上边数组里按照顺序, 取出中文的名字, 但是对应数组值的数组, 要从英文key对象中取出value值, 我要用中文key换到英文key然后去取到值)
      const myObj = {
        // 序号可以等遍历的时候直接用索引值, 而不是来自于英文对象里
        姓名: 'username',
        头像: 'staffPhoto',
        手机号: 'mobile',
        工号: 'workNumber',
        聘用形式: 'formOfEmployment',
        部门: 'departmentName',
        入职时间: 'timeOfEntry'
      }
      // 4.2 按照顺序, 形成值的数组 (明确目标->想要数据结构->读代码(每个变量意思)读2-3遍->仿写3-5遍)
      const resultArr = rows.map((item, index) => {
        const valueArr = [] // 值小数组
        headerArr.forEach((zhKey) => {
          if (zhKey === '序号') {
            valueArr.push(index + 1)
          } else if (zhKey === '聘用形式') {
            const enKey = myObj[zhKey]
            if (Number(item[enKey]) === 1) {
              item[enKey] = '正式'
            } else if (Number(item[enKey]) === 2) {
              item[enKey] = '非正式'
            } else {
              item[enKey] = '未知'
            }
            valueArr.push(item[enKey])
          } else {
            const enKey = myObj[zhKey]
            valueArr.push(item[enKey])
          }
        })
        return valueArr
      })
      return { header: headerArr, data: resultArr }
    },

    // 导出 Excel
    async handleDownload() {
      const res = await getStaffInfoAPI(this.query)
      const res2 = await getStaffInfoAPI({
        page: 1,
        size: res.data.total
      })
      const excelObj = this.transData(res2.data.rows)
      import('@/vendor/Export2Excel').then((excel) => {
        // excel表示导入的模块对象
        excel.export_json_to_excel({
          header: excelObj.header, // 表头 必填
          data: excelObj.data, // 具体数据 必填
          filename: '员工列表', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },

    // 获取角色列表
    async getRoleList() {
      const res = await getRoleListAPI({ page: 1, pagesize: 1 })
      const allRes = await getRoleListAPI({ page: 1, pagesize: res.data.total })
      console.log(allRes)
      this.roleList = allRes.data.rows
    },

    // 显示角色权限弹框
    async showRoleDialogFn(row) {
      this.showRoleDialog = true
      this.roleId = row.id
      const res = await getStaffDetailAPI(row.id)
      console.log(res)
      this.$nextTick(() => {
        this.$refs.roleDialog.checkList = res.data.roleIds
      })
    },

    // 保存用户权限
    async assignRoles(checkList) {
      const res = await assignRolesAPI({
        roleIds: checkList,
        id: this.roleId
      })
      console.log(res)
    }
  }
}
</script>

<style lang="scss" scoped>
.employees-container {
  img {
    width: 60px;
    height: 60px;
    border-radius: 50%;
  }
}
</style>
